package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.SensitiveDto;
import com.heima.media.entity.WmSensitive;
import com.heima.media.mapper.WmSensitiveMapper;
import com.heima.media.service.IWmSensitiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 敏感词信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-13
 */
@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements IWmSensitiveService {
    /**
     * 按照敏感词模糊查询 或分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult sensitiveList(SensitiveDto dto) {
        //判断参数是否为空
        if(dto==null||dto.getPage()==null||dto.getSize()==null){
            //返回无效参数
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //构建查询条件
        LambdaQueryWrapper<WmSensitive> query=new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(dto.getName())){
            query.like(WmSensitive::getSensitives,dto.getName());
        }
        //排序
        query.orderByDesc(WmSensitive::getCreatedTime);
        //分页条件
        IPage<WmSensitive> page=new Page<>(dto.getPage(),dto.getSize());
        //分页查询
        IPage<WmSensitive> iPage = this.page(page, query);
        PageResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
        return result;
    }

    /**
     * 新增 修改敏感词
     * @param wmSensitive
     * @return
     */
    @Override
    public ResponseResult saveSensitive(WmSensitive wmSensitive) {
        //判断参数是否为空
        if(StringUtils.isEmpty(wmSensitive.getSensitives())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询敏感词是否已经存在
        //构建查询条件,根据敏感词查询
        LambdaQueryWrapper<WmSensitive> query=new LambdaQueryWrapper<>();
        query.eq(WmSensitive::getSensitives,wmSensitive.getSensitives());
        WmSensitive one = this.getOne(query);
        //如果已经存在
        if(one!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //不存在添加
        wmSensitive.setCreatedTime(new Date());
        this.saveOrUpdate(wmSensitive);//存在id时修改
        return ResponseResult.okResult();
    }
}
